package com.gm.wholesale.module.setting.view;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.wholesale.R;
import com.gm.wholesale.bluetooth.BluetoothUtil;
import com.gm.wholesale.bluetooth.bean.DeviceBean;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class BluetoothListView extends LinearLayout {
    private Context mContext;
    private ListView mListView;
    private OnItemClickListener listener;
    private LinearLayout mProgressBarView;
    private List<String> filters;

    private MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
    ;
    private CommonAdapter adapter;
    private String mConnectionDevice;
    private List<DeviceBean> mDeviceBeans = new ArrayList<>();

    public synchronized void showDevice(List<String> filters, String connectionDevice) {
        mConnectionDevice = connectionDevice;
        mDeviceBeans.clear();

         if (filters!=null){
             for (String filter:filters){
                 Set<DeviceBean> mConnectionDevices = BluetoothUtil.newInstance().getConnectDevices(mContext, filter);
                 if (mConnectionDevices != null && !mConnectionDevices.isEmpty()) {
                     mDeviceBeans.addAll(mConnectionDevices);
                 }
             }
         }

        if (myBroadcastReceiver != null
                && myBroadcastReceiver.isOrderedBroadcast()) {
            mContext.unregisterReceiver(myBroadcastReceiver);
        }

        this.filters = filters;
        BluetoothUtil.newInstance().startFindDevice(mContext,
                myBroadcastReceiver);
        showProgressBar();
        showView();

    }


    class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                }
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    String deviceName = device.getName();
                    if (filters == null || filters.isEmpty()) {
                        setDevice(context, device);
                    } else if (filters.size() == 1) {
                        if (deviceName!=null && deviceName.startsWith(filters.get(0))){
                            setDevice(context, device);
                        }
                    } else {
                        boolean find=false;
                        if (deviceName!=null){
                            for (String filter:filters){
                                if (deviceName.startsWith(filter)){
                                    find=true;
                                }
                            }
                            if (find){
                                setDevice(context,device);
                            }
                        }
                    }

                }

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (listener != null) {
                    showView();
                    findFinish();
                }
            }

        }
    }

    private void setDevice(Context context, BluetoothDevice device) {
        DeviceBean deviceBean = new DeviceBean();
        deviceBean.setAddress(device.getAddress());
        BluetoothUtil.setDevice(context,device,deviceBean);
        addDevice(deviceBean);
        if (listener != null) {
            showView();
        }
    }

    private void addDevice(DeviceBean deviceBean) {
        boolean isExit = false;
        if (mDeviceBeans != null) {
            for (DeviceBean deviceBean1 : mDeviceBeans) {
                if (deviceBean1.getName().equals(deviceBean.getName())) {
                    isExit = true;
                }

            }
            if (!isExit) {
                mDeviceBeans.add(deviceBean);
            }
        }
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(DeviceBean deviceBean);
    }

    public BluetoothListView(Context context) {
        super(context);
        initView(context);
    }

    public BluetoothListView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.view_setting_bluetooth, this);
        mProgressBarView = findViewById(R.id.progressBarView);
        mListView = findViewById(R.id.listView);
    }


    public void findFinish() {
        mProgressBarView.setVisibility(GONE);
    }

    public void showProgressBar() {
        mProgressBarView.setVisibility(View.VISIBLE);
    }

    public void notifyDataSetChanged(String connectionDevice) {
        mConnectionDevice = connectionDevice;
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    private void showView() {
        if (adapter != null) {
            adapter.notifyDataSetChanged();
            return;
        }
        adapter = new CommonAdapter<>(mContext, mDeviceBeans, R.layout.view_setting_bluetooth_item) {
            @Override
            public void convert(ViewHolder viewHolder, DeviceBean deviceBean) {
                viewHolder.setText(R.id.blueNameTv, deviceBean.getName());
                TextView blueStateTv = viewHolder.getView(R.id.blueStateTv);
                if (!TextUtils.isEmpty(mConnectionDevice)
                        && deviceBean.getAddress().equals(mConnectionDevice)) {
                    deviceBean.setState(1);
                    viewHolder.setText(R.id.blueStateTv, "已连接");
                    blueStateTv.setTextColor(mContext.getResources().getColor(R.color.color_06C160));
                } else {
                    deviceBean.setState(0);
                    viewHolder.setText(R.id.blueStateTv, "未连接");
                    blueStateTv.setTextColor(mContext.getResources().getColor(R.color.color_666));
                }
                viewHolder.getConvertView().setOnClickListener(view -> {
                    if (listener != null) {
                        listener.onItemClick(deviceBean);
                    }

                });
            }
        };
        mListView.setAdapter(adapter);
    }

    public void stop() {
        try {
            if (mContext != null && myBroadcastReceiver != null) {
                mContext.unregisterReceiver(myBroadcastReceiver);
            }
            mDeviceBeans.clear();
            adapter = null;
            mContext = null;
        } catch (Exception e) {

        }


    }

}
